import { ref, reactive, toRefs } from "vue";
import { ElNotification as NOT } from "element-plus";
import type { FormInstance } from "element-plus";
import { v4 as uuid4 } from "uuid";
import { getAction, postAction } from "@/api/request";

interface pageDataType {
  response: objectType<any>;
  dataSourse: objectType<any>[];
  pageSourse: pageType;
  queryPrams: objectType<any>;
}
let pageData: pageDataType = reactive({
  response: {},
  dataSourse: [],
  pageSourse: {
    limit: 20,
    pages: 1,
    current: 1,
    total: 1,
  },
  queryPrams: {
    current: 1,
    limit: 20,
  },
});
let oldUrl = ref("");
export default function usePageListData() {
  /**
   * 请求列表数据
   * @param url 列表Api 必传
   * @param type 检索类型 选传(当为search时 将页码置为1请求数据)
   * @param methods 请求方式 选传(默认为post)
   */
  function getListData(url: string, type?: string, methods = "post") {
    if (type === "search" || oldUrl.value !== url) {
      pageData.queryPrams.current = 1;
      pageData.queryPrams.limit = 20;
    }
    if (url) {
      let requeryList = methods === "post" ? postAction : getAction;
      requeryList(url, pageData.queryPrams).then(
        (res: BaseResponse<BaseListType>) => {
          if (res.header.code === 999) {
            oldUrl.value = url;
            pageData.dataSourse = [];
            pageData.response = res.body;
            filterList({ ...res.body });
          } else {
            pageData.dataSourse = [];
          }
        }
      );
    } else {
      NOT({
        title: "系统消息",
        type: "error",
        message: "请设置listUrl属性",
      });
    }
  }

  /**
   * 数据格式化
   * @param response 列表接口返回的数据 必传
   */
  function filterList(response: BaseListType) {
    pageData.dataSourse = response.data.map((item: objectType<any>) => {
      item.uid = uuid4();
      return item;
    });
    pageData.pageSourse = response.pageInfo;
    console.log(pageData.dataSourse, pageData.pageSourse, "数据改变");
  }

  /**
   * 重置按钮
   * @param modelForm 检索实例 必传
   * @param defaulQueryPrams 默认值设置 选传
   */
  function handleReset(
    modelForm: FormInstance,
    defaulQueryPrams = {},
    url: string
  ) {
    modelForm.resetFields();
    pageData.queryPrams = { ...defaulQueryPrams };
    getListData(url);
  }

  // 计算table的高度
  function computedTableHeight(searchBox: any, actionHeight?: number) {
    let clientHeight = document.body.clientHeight;
    let height =
      clientHeight - 60 - searchBox.clientHeight - 80 - (actionHeight || 0);
    console.log("当前页面table高度为：", height);
    return height;
  }

  return {
    ...toRefs(pageData),
    handleReset,
    getListData,
    computedTableHeight,
  };
}
